<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>新闻管理</el-breadcrumb-item>
      <el-breadcrumb-item>新闻展示</el-breadcrumb-item>
    </el-breadcrumb>
    <div style="margin-top: 30px">
      <el-form :inline="true" :model="newsForm" ref="newsForm" class="demo-form-inline">
        <el-form-item label="新闻标题">
          <el-input v-model="searchName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
      <!-- 新增，发布新闻 -->
      <el-row>
        <el-button type="primary" plain @click="dialogFormVisible=true">发布新闻</el-button>
        <el-button :disabled="isAllDel" type="danger" plain @click="toggleSelection">批量删除</el-button>
      </el-row>
      <el-dialog v-dialog-drag title="发布任务" :visible.sync="dialogFormVisible">
        <div>
          <el-form :model="newsForm" ref="newsForm" label-width="100px">
            <el-form-item label="新闻标题" prop="newsTitle">
              <el-input clearable="clearable" v-model="newsForm.newsTitle"></el-input>
            </el-form-item>
            <el-form-item label="新闻内容" prop="newsContent">
              <el-input type="textarea" v-model="newsForm.content"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div style="border-radius: 2px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);">
      <el-table
        ref="multipleTable"
        v-loading="isLoading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        :data="tableData"
        style="width: 100%; margin-top: 10px;"
        max-height="400"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column
          fixed
          prop="newsTitle"
          label="新闻标题"
          width="150">
        </el-table-column>
        <el-table-column
          prop="views"
          label="浏览量"
          width="200">
        </el-table-column>
        <el-table-column
          prop="content"
          label="内容"
          width="600">
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="200">
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="deleteRow(scope.$index, tableData)"
              type="text"
              size="small">
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageTotal">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import loading from "@/components/loading";
import {getNews, create, del, search} from "@/api/news";
import store from "@/store";

export default {
  inject: ['reload'],
  name: "news",
  components: { loading },
  mounted() {
    this.isLoading = true
    this.getNews()
  },
  methods: {
    async search(){
      this.tableData = []
      console.log(this.searchName)
      const response = await search({newsTitle: this.searchName})
      this.tableData = response.data.list
      console.log(this.tableData)
    },

    async getNews() {
      this.isLoading = false
      this.newsForm['pageNum'] = this.pageNum
      this.newsForm['pageSize'] = this.pageSize
      const response = await getNews(this.pageNum, this.pageSize)
      console.log('this the news：',response)
      this.pageNum = response.data.pageNum
      this.pageSize = response.data.pageSize
      this.pageTotal = response.data.total
      this.tableData = response.data.list
    },
    onSubmit() {
      console.log('submit!');
    },
    deleteRow(index, rows) {
      console.log('the index:',index, 'the rows:',rows)
      rows.splice(index, 1);
    },
    // 时间戳转换成时间
// 使用element table组件中的formatter属性，传入一个函数
    timestampToTime (row, column) {
      var date = new Date(row[column.property]) //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '-'
      var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'
      var D = date.getDate() + ' '
      var h = date.getHours() + ':'
      var m = date.getMinutes() + ':'
      var s = date.getSeconds()
      return Y+M+D+h+m+s
    },
    async handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.isLoading = true
      const response = await getNews(this.pageNum, val)
      this.pageNum = response.data.pageNum
      this.pageSize = response.data.pageSize
      this.pageTotal = response.data.total
      await this.getNews()
    },
    async handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.isLoading = true
      const response = await getNews(val, this.pageSize)
      this.pageNum = val
      this.pageSize = response.data.pageSize
      this.pageTotal = response.data.total
      await this.getNews()
    },
    toggleSelection() {
      console.log('我按了删除键', this.someDelNewsIds)
      const vals = this.someDelNewsIds
      for (let i = 0; i < vals.length; i++) {
        this.delOne(vals[i])
      }
      this.$notify({
        title: '成功',
        message: '删除成功，请刷新看一看叭。',
        type:'success'
      })
      this.reload()
    },
    handleSelectionChange(val) {
      this.someDelNewsIds = []
      if (val.length > 0){
        this.isAllDel = !this.isAllDel
        this.multipleSelection = val;
      }else{
        this.isAllDel = true
      }
      for (let i = 0; i < val.length; i++) {
        this.someDelNewsIds.push(val[i].id)
      }
    },
    async delOne(id){
      await del(id)
    },
    async submitForm() {
      await store.dispatch('user/getInfo').then(data => {
        this.newsForm.creator = data.id
        const response = create(this.newsForm);
        this.$notify({
          title: '发布成功',
          message: '发布新闻成功',
          type: 'success'
        });
        this.dialogFormVisible = false
        this.reload();
      })
    },
  },
  data() {
    return {
      someDelNewsIds: [],
      //
      // search name:
      searchName: '',
      isAllDel: true,
      // task
      pageNum: 1,
      pageSize: 5,
      pageTotal: 5,
      newsForm: {
        creator: '',
        newsTitle: '',
        content: '',
        author: '未知',
        createTime: '',
        views: 0
      },
      //
      dialogTableVisible: false,
      dialogFormVisible: false,
      // ++++++++++++++++++++++++
      multipleSelection: [],
      isLoading: false,
      tableData: [],
    }
  }
}
</script>

<style scoped>

</style>
